package util;

import java.text.SimpleDateFormat;
import java.util.Calendar;

public class StopWatch {

	public static final String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss.SSS";

	private Calendar cal;

	private long initialtime;

	private long finishtime;

	private boolean running;

	private String text;

	public StopWatch() {
		this.cal = Calendar.getInstance();
		this.initialtime = 0;
		this.finishtime = 0;
		this.running = false;
		this.text = "";
	}

	public static String getCurrentTime() {
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
		return sdf.format(cal.getTime());
	}

	public void reset() {
		this.initialtime = 0;
		this.finishtime = 0;
		this.running = false;
		this.text = "";
	}

	public void start() throws SSIDException {
		if (this.running) {
			throw new SSIDException("The stopwatch is running.");
		} else {
			this.initialtime = this.cal.getTimeInMillis();
			this.running = true;
			this.text = "";
		}
	}

	public void stop() throws SSIDException {
		if (this.running) {
			this.finishtime = this.cal.getTimeInMillis();
			this.running = false;
			this.text = new String((float) (this.finishtime - this.initialtime)
					/ 1000 + " seconds");
		} else {
			throw new SSIDException("The stopwatch has not started yet.");
		}
	}

	public String getText() {
		return this.text;
	}
}
